package com.mhs.map;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.mhs.DTO.PlacemarkDTO;
import com.mhs.mhs_gui.R;
import com.mhs.mydialog.MyDialogListner;

public class SearchLocation extends MapActivity {

	private static final String TAG = SearchLocation.class.getName();

	EditText edtLocationSearchName;
	Button btnSearchLocation;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.mapsearchlocation);

		edtLocationSearchName = (EditText) findViewById(R.id.edtLocationNameSearch);
		btnSearchLocation = (Button) findViewById(R.id.btnSearchLocation);
		btnSearchLocation.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				myOnClick(v);
			}
		});
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public void myOnClick(View view) {
		switch (view.getId()) {
		case R.id.btnSearchLocation:
			String address = edtLocationSearchName.getText().toString().trim();
			address = "bệnh viện";
			if (address.isEmpty()) {
				MyDialogListner.ShowMessageAlert(this,
						"Chưa nhập keyword tìm kiếm!");
			} else {
				if (checkCharacters(address, " ")) {
					// address = address.replaceAll(" ", "%20");
					String[] arrTemp = address.split(" ");
					getKMLFileFromGoogleMap(arrTemp);
					// JSONObject jsonResonse = getLocationInfo(address);
					// if(jsonResonse != null){
					// @SuppressWarnings("unused")
					// GeoPoint geoPoint = getGeoPoint(jsonResonse);
					//
					// }
				} else {
					MyDialogListner.ShowMessageAlert(this,
							"Vui lòng nhập lại keyword!");
				}

			}

			break;
		default:
			break;
		}
	}

	public void getKMLFileFromGoogleMap(String[] arrTemp) {
		String keyWord = arrTemp[0] + "+" + arrTemp[1];
		// https://maps.google.com/maps?q=benh+vien&sll=10.835277,106.662707&num=5&output=kml
		String urlAddress = "https://maps.google.com/maps?q=" + keyWord
				+ "&sll=10.835277,106.662707&num=1&output=kml";
		HttpGet httpGet = new HttpGet(urlAddress);
		HttpClient client = new DefaultHttpClient();
		HttpResponse response;
		try {
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = null;
			try {
				db = dbf.newDocumentBuilder();
				Document dom = db.parse(stream);
				processDocumentKML(dom);
			} catch (ParserConfigurationException e) {
				MyDialogListner.ShowMessageAlert(this,
						"Có lỗi xảy ra, vui lòng thử lại!");
				e.printStackTrace();
				return;
			} catch (SAXException e) {
				MyDialogListner.ShowMessageAlert(this,
						"Có lỗi xảy ra, vui lòng thử lại!");
				e.printStackTrace();
				return;
			}
		} catch (ClientProtocolException e) {
			MyDialogListner.ShowMessageAlert(this,
					"Có lỗi xảy ra, vui lòng thử lại!");
			// e.printStackTrace();
			return;

		} catch (IOException e) {
			MyDialogListner.ShowMessageAlert(this,
					"Có lỗi xảy ra, vui lòng thử lại!");
			e.printStackTrace();
			return;
		}
	}

	private void processDocumentKML(Document documentKML) {
		NodeList lstNodePlaceMark = documentKML
				.getElementsByTagName("Placemark");
		List<PlacemarkDTO> lstPlaceMark = new ArrayList<PlacemarkDTO>();
		if (lstNodePlaceMark.getLength() == 0 || lstNodePlaceMark == null) {
			MyDialogListner.ShowMessageAlert(this,
					"Không thông tin bệnh viện xung quanh vị trí của bạn!");
			return;
		} else if (lstNodePlaceMark.getLength() > 0
				&& (lstNodePlaceMark != null)) {
			for (int i = 0; i < lstNodePlaceMark.getLength(); i++) {
				Element element = (Element) lstNodePlaceMark.item(i);
				PlacemarkDTO placeMarkDTO = new PlacemarkDTO();
				NodeList lstNodeName = element.getElementsByTagName("name");
				if (lstNodeName.getLength() == 1) {
					String valueOfNodeName = lstNodeName.item(0)
							.getTextContent().trim();
					placeMarkDTO.setName(valueOfNodeName);
				}
				NodeList lstAddress = element.getElementsByTagName("address");
				if (lstAddress.getLength() == 1) {
					String valueOfNodeAdd = lstAddress.item(0).getTextContent()
							.trim();
					String[] arrTemp = valueOfNodeAdd.split("<br/>");
					valueOfNodeAdd = "";
					valueOfNodeAdd = arrTemp[0] + "," + arrTemp[1];
					valueOfNodeAdd = valueOfNodeAdd.replaceAll("<br/>", ",");
					placeMarkDTO.setAddress(valueOfNodeAdd);

				}
				NodeList lstCoordinate = element
						.getElementsByTagName("coordinates");
				if (lstCoordinate.getLength() == 1) {
					String valueOfNodeCoor = lstCoordinate.item(0)
							.getTextContent().trim();
					if (checkCharacters(valueOfNodeCoor, ",")) {
						String[] arrTemp = valueOfNodeCoor.split(",");
						placeMarkDTO.setLatitude(arrTemp[1].trim());
						placeMarkDTO.setLongitude(arrTemp[0].trim());
					}
				}
				lstPlaceMark.add(placeMarkDTO);
			}
		}
	}

	public JSONObject getLocationInfo(String address) {
		HttpGet httpGet = new HttpGet("http://maps.google."
				+ "com/maps/api/geocode/json?address=" + address
				+ "&sensor=false");
		httpGet.setHeader("Accept-Charset", "utf-8");
		HttpClient client = new DefaultHttpClient();
		HttpResponse response;
		StringBuilder stringBuilder = new StringBuilder();

		try {
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			InputStreamReader isr = new InputStreamReader(stream, "UTF-8");
			int b;
			while ((b = isr.read()) != -1) {
				stringBuilder.append((char) b);
			}
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject = new JSONObject(stringBuilder.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return jsonObject;
	}

	public GeoPoint getGeoPoint(JSONObject jsonObject) {

		Double lon = new Double(0);
		Double lat = new Double(0);

		try {

			lon = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
					.getJSONObject("geometry").getJSONObject("location")
					.getDouble("lng");

			lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
					.getJSONObject("geometry").getJSONObject("location")
					.getDouble("lat");

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));

	}

	public boolean checkCharacters(String query, String characterCheck) {
		boolean check = false;
		char[] cArray = convertStringToCharArray(query);
		for (int i = 0; i < cArray.length; i++) {
			if (Character.toString(cArray[i]).compareTo(characterCheck) == 0) {
				check = true;
				break;
			} else {
				check = false;
			}
		}
		return check;
	}

	public boolean checkString(String query, String stringCheck) {
		boolean check = false;
		query = query.trim().toLowerCase();
		String[] arrTemp = query.split(" ");
		for (int i = 0; i < arrTemp.length; i++) {
			if (arrTemp[i].trim().compareTo(stringCheck) == 0) {
				check = true;
				break;
			} else {
				check = false;
			}
		}
		return check;
	}

	public char[] convertStringToCharArray(String query) {
		return query.toCharArray();
	}

	public Document loadXMLFrom(String xml) throws Exception {
		InputSource is = new InputSource(new StringReader(xml));
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder = null;
		builder = factory.newDocumentBuilder();
		Document doc = builder.parse(is);
		return doc;
	}
}
